package org.openwp3x.iclazz;

import org.json.JSONArray;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;

public class MainApp extends Activity {

	Button button;

	EditText query;

	AdGridAdapter adGridAdapter;

	@Override
	public void onCreate(final Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.app);

		initComponents();
	}

	private void initComponents() {
		this.button = (Button) findViewById(R.id.btnSearch);
		this.query = (EditText) findViewById(R.id.txtComments);

		this.adGridAdapter = new AdGridAdapter(this);
		// this.query.setText("bicicleta vermelha");
		this.button.setOnClickListener(new View.OnClickListener() {
			public void onClick(final View v) {
				search();
			}
		});
	}

	private void search() {
		try {
			RestClient client = new RestClient(IClazz.getURL("/search/json"));
			client.AddParam("q", MainApp.this.query.getText().toString());

			client.Execute(RequestMethod.GET);

			String response = client.getResponse();

			JSONObject json = new JSONObject(response);

			JSONArray list = json.getJSONArray("list");

			ListView listAd = (ListView) findViewById(R.id.listAd);
			listAd.setClickable(true);
			listAd.setOnItemClickListener(new OnClick(this));

			MainApp.this.adGridAdapter.setList(list);
			listAd.setAdapter(MainApp.this.adGridAdapter);
			// gridview.refreshDrawableState();

		} catch (Exception e) {
			AlertDialog alertDialog = new AlertDialog.Builder(this).create();
			Log.i("teste", "erro");
			alertDialog.setMessage(e.getMessage());
			alertDialog.show();
		}
	}

	public static class OnClick implements OnItemClickListener {
		Context context;

		public OnClick(final Context context) {
			this.context = context;
		}

		public void onItemClick(final AdapterView<?> adapterView, final View view, final int arg2, final long arg3) {
			ViewHolder holder = (ViewHolder) view.getTag();
			/*
			 * AlertDialog alertDialog = new AlertDialog.Builder(this.context).create(); alertDialog.setMessage(holder.id + " " + holder.adDesc); alertDialog.show();
			 */
			Intent intent = new Intent();
			intent.setClassName("org.openwp3x.iclazz", "org.openwp3x.iclazz.ViewAd");
			intent.putExtra("adId", holder.adId);
			intent.putExtra("adDesc", holder.adDesc.getText());
			intent.putExtra("publisherId", holder.publisherId);
			intent.putExtra("publisherName", holder.publisherName.getText());
			intent.putExtra("publisherEmail", holder.publisherEmail);

			this.context.startActivity(intent);

		}
	}
}